import 'package:flutter/material.dart';
import '../../services/mock_data_service.dart';
import '../../models/maintenance_models.dart';

class MaintenanceDataWidget extends StatefulWidget {
  const MaintenanceDataWidget({super.key});

  @override
  State<MaintenanceDataWidget> createState() => _MaintenanceDataWidgetState();
}

class _MaintenanceDataWidgetState extends State<MaintenanceDataWidget> {
  Map<String, List<dynamic>> maintenanceData = {};
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadMaintenanceData();
  }

  Future<void> _loadMaintenanceData() async {
    try {
      final data = await MockDataService.getMaintenanceData();
      setState(() {
        maintenanceData = data;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      // 可以添加错误处理
      print('加载维护数据失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Center(
        child: CircularProgressIndicator(
          color: Color(0xFF0A79DF),
        ),
      );
    }
    
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildMaintenanceSection('智能送风口控制', Icons.air, maintenanceData['smartAirOutletControl'] ?? []),
          const SizedBox(height: 12),
          _buildMaintenanceSection('送风口高效使用累计时间复位清零', Icons.timer, maintenanceData['airOutletUsageTimeReset'] ?? []),
          const SizedBox(height: 12),
          _buildMaintenanceSection('房间压差控制', Icons.compress, maintenanceData['roomPressureDifferenceControl'] ?? []),
          const SizedBox(height: 12),
          _buildMaintenanceSection('房间排风控制', Icons.air_outlined, maintenanceData['roomExhaustControl'] ?? []),
          const SizedBox(height: 12),
          // XF-01和XF-02空调机组信息表 - 左右布局
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: _buildMaintenanceSection('XF-01预处理空调机组信息', Icons.hvac, maintenanceData['xf01AirConditionerUnitControl'] ?? []),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildMaintenanceSection('XF-02灌装空调机组信息', Icons.hvac, maintenanceData['xf02AirConditionerUnitControl'] ?? []),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildMaintenanceSection(String title, IconData icon, List<dynamic> data) {
    if (data.isEmpty) {
      return Container(
        decoration: BoxDecoration(
          color: const Color(0xFF0B1A3E).withOpacity(0.8),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: const Color(0xFF0A79DF).withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 栏目标题
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: const BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFF0A79DF),
                    width: 2,
                  ),
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    icon,
                    color: const Color(0xFF0A79DF),
                    size: 16,
                  ),
                  const SizedBox(width: 8),
                  Container(
                    width: 1,
                    height: 16,
                    color: const Color(0xFF0A79DF),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
            // 无数据提示
            Container(
              padding: const EdgeInsets.symmetric(vertical: 16),
              child: const Center(
                child: Text(
                  '暂无维护数据',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF0B1A3E).withOpacity(0.8),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: const Color(0xFF0A79DF).withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 栏目标题
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: const BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0xFF0A79DF),
                  width: 2,
                ),
              ),
            ),
            child: Row(
              children: [
                Icon(
                  icon,
                  color: const Color(0xFF0A79DF),
                  size: 16,
                ),
                const SizedBox(width: 8),
                Container(
                  width: 1,
                  height: 16,
                  color: const Color(0xFF0A79DF),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    title,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
          // 维护数据显示
          Padding(
            padding: const EdgeInsets.all(8),
            child: LayoutBuilder(
              builder: (context, constraints) {
                // 动态计算每行的项目数量，确保最小宽度
                const minItemWidth = 120.0;
                final maxItemsPerRow = (constraints.maxWidth / minItemWidth).floor().clamp(1, 4);
                final itemWidth = (constraints.maxWidth - (maxItemsPerRow - 1) * 4.0) / maxItemsPerRow;
                return Wrap(
                  spacing: 4.0,
                  runSpacing: 4.0,
                  children: data.map((item) {
                    String displayName = '';
                    String displayInfo = '';
                    
                    // 根据不同的维护数据类型获取显示信息
                    if (item.runtimeType.toString().contains('SmartAirOutletControl')) {
                      displayName = item.name ?? '';
                      displayInfo = '${item.tag ?? ''} (${item.address ?? ''})';
                    } else if (item.runtimeType.toString().contains('AirOutletUsageTimeReset')) {
                      displayName = item.name ?? '';
                      displayInfo = '${item.tag ?? ''} (${item.address ?? ''})';
                    } else if (item.runtimeType.toString().contains('RoomPressureDifferenceControl')) {
                      displayName = item.name ?? '';
                      displayInfo = '${item.tag ?? ''} (${item.address ?? ''})';
                    } else if (item.runtimeType.toString().contains('RoomExhaustControl')) {
                      displayName = item.name ?? '';
                      displayInfo = '${item.tag ?? ''} (${item.address ?? ''})';
                    } else if (item.runtimeType.toString().contains('AirConditionerUnitControl')) {
                      displayName = item.name ?? '';
                      displayInfo = '${item.tag ?? ''} (${item.address ?? ''})';
                    } else {
                      displayName = item.toString();
                      displayInfo = '';
                    }
                    
                    return SizedBox(
                      width: itemWidth,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color(0xFF0B1A3E),
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(
                            color: const Color(0xFF0A79DF).withOpacity(0.3),
                            width: 1,
                          ),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                width: 8,
                                height: 8,
                                decoration: BoxDecoration(
                                  color: const Color(0xFF0A79DF),
                                  borderRadius: BorderRadius.circular(4),
                                  boxShadow: [
                                    BoxShadow(
                                      color: const Color(0xFF0A79DF).withOpacity(0.3),
                                      blurRadius: 6,
                                      spreadRadius: 2,
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(width: 6),
                              Flexible(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      displayName,
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontSize: 10,
                                        fontWeight: FontWeight.w500,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    if (displayInfo.isNotEmpty)
                                      Text(
                                        displayInfo,
                                        style: TextStyle(
                                          color: Colors.white.withOpacity(0.7),
                                          fontSize: 8,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}